<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"

            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-allow="'addEmployee'"
            type="primary"
            size="small"

            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{ prop: 'timeOfEntry', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column
            label="姓名"
            prop="username"
          />
          <el-table-column label="员工头像">
            <template #default="{row}">
              <img
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showQrCode(row.staffPhoto)"
              >

            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatData(row.formOfEmployment ) }}
            </template>

          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />

          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="assignRole(row.id)"
              >分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增部门" :visible.sync="showDialog">
        <addEmployees @close="showDialog =false" @success="hSuccess" />
      </el-dialog>
      <el-dialog title="生成二维码" :visible.sync="showCodeDialog">
        <el-row>
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog

        title="分配角色"
        :visible.sync="showRoleDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <AssignRole
          v-if="showRoleDialog"
          :cur-id="curId"
          @success="showRoleDialog=false"
          @close="showRoleDialog =false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import { transZhkeyToExcel } from '@/utils'
import addEmployees from '@/views/employees/empDialog.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import AssignRole from './assignRole.vue'
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addEmployees,
    AssignRole
  },
  data() {
    return {
      showRoleDialog: false,
      showCodeDialog: false,
      list: [],
      curId: '',
      page: 1,
      size: 4,
      total: 0,
      showDialog: false
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {

    assignRole(id) {
      this.curId = id
      this.showRoleDialog = true
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        // await this.loadEmployees()
        const { tHeader, data } = transZhkeyToExcel(this.list)
        console.log(data, tHeader)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx'
        })
      })
    },
    async hDel(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.list.length <= 0) {
            this.page === 1
          }
        }
        if (res.code !== 10000) return this.$message.error(res.message)

        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.loadEmployees()
      }).catch((error) => {
        this.$message.error(error)
      })
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      const pageMax = Math.ceil(this.total / this.page)

      this.page = pageMax

      this.loadEmployees()
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployees()
    },
    formatData(id) {
      return hireType[id] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log(res, 'getEmployees')
        if (res.code !== 10000) return this.$message.error(res.message)
        // this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
